<template>
  <div class="w1 h1 main_content">
    <div class="search-content">
      <Col class="panel search-panel" span="24">
      <Form :model="formHeader" :label-width="100" inline>
        <FormItem label="企业名称：" v-if="userRole!='ROLE_DEMO'">
          <Select style="width: 200px;" clearable v-model="formHeader.companyId" @on-change="_companyChange">
            <Option v-for="company in companyList" :key="company.index" :value="company.id" :label="company.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="企业名称：" v-if="userRole=='ROLE_DEMO'">
          <Select style="width: 200px;" clearable v-model="formHeader.companyId" @on-change="_companyChange">
            <Option v-for="company in companyList" :key="company.index" :value="company.id" :label="!!company.alias?company.alias:company.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称：" v-if="userRole!='ROLE_DEMO'">
          <Select v-model="formHeader.deviceId" clearable style="width:200px">
            <Option v-for="device in deviceList" :value="device.id" :key="device.index" :label="device.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称：" v-if="userRole=='ROLE_DEMO'">
          <Select v-model="formHeader.deviceId" clearable style="width:200px">
            <Option v-for="device in deviceList" :value="device.id" :key="device.index" :label="!!device.alias?device.alias:device.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="日期：">
          <DatePicker style="width:200px;" :clearable="false" type="daterange" v-model="formHeader.timeRange" format="yyyy/MM/dd" :options="timeOptions" placement="right-start" placeholder="请选择日期"></DatePicker>
        </FormItem>
        <FormItem class="margin-left-20">
          <Button type="primary" @click="_requireThing">查询</Button>
        </FormItem>
      </Form>
      </Col>
    </div>
    <div class="w1 scroll__content offline_content">
      <Row class="scroll-content__row">
        <!-- 表格 -->
        <Col class="panel table-panel" :span="24">
        <Table :columns="userRole=='ROLE_DEMO'?columnsOfDemo: columns" :data="tableData" border :loading="pageInfo.loading"></Table>
        </Col>
        <!-- 分页 -->
        <Col class="panel page-panel cf" :span="24" style="margin-bottom: 10px;">
        <Page :total="pageInfo.total" show-total :current.sync="pageInfo.page" class="fr" @on-change="switchThePaging" :page-size="20"></Page>
        </Col>
        <Col span="24" class="page-bottom">
        </Col>
      </Row>
    </div>
    <Modal v-model="modal" title="原因提交">
      <Form :model="selectRow" label-width="100" ref="formRef" :rules="formRules">
        <FormItem label="设备ID：">
          <Input v-model="selectRow.deviceNo" :disabled="true"></Input>
        </FormItem>
        <FormItem label="事件时间：">
          <Input v-model="selectRow.eventDate" :disabled="true"></Input>
        </FormItem>
        <FormItem label="掉线类型：" prop="type">
          <Select v-model="selectRow.type">
            <Option v-for="(item,index) in types" :value="item.id" :key="index" :label="item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="客服姓名：" prop="customerName">
          <Input v-model="selectRow.customerName" maxlength="5"></Input>
        </FormItem>
        <FormItem label="备注：" prop="remark">
          <Input v-model.trim="selectRow.remark" type="textarea" placeholder=" 请输入备注...." />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modal = false">取消</Button>
        <Button type="primary" @click="_confirmAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>


<script>
import tableExpand from "./components/table-expand";
import {
  getDeviceLogList,
  getCityList,
  getCompanyListByCity,
  getDeviceListByCompany,
  addServiceLog
} from "@/api";

import format from "@/utils/format";

import { validateAddress, validateTitle } from "@/utils/rules";
import { mapState } from "vuex";
export default {
  components: {
    tableExpand
  },
  mounted() {
    let vm = this;
    // vm._getCityList();
    vm._getCompanyList();
    vm._getDeviceLogList();
  },
  computed: {
    ...mapState({
      userRole: state => state.userInfo.rname
    })
  },
  data() {
    return {
      types: [
        {
          id: 0,
          name: "断电"
        },
        {
          id: 1,
          name: "信号差"
        },
        {
          id: 2,
          name: "设备故障"
        }
      ],
      modal: false,
      selectRow: {},
      timeOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      cityList: [],
      deviceList: [],
      companyList: [],
      formHeader: {
        cityId: "",
        companyId: "",
        deviceId: "",
        timeRange: [
          this.moment()
            .add(-7, "days")
            .format(),
          this.moment()
            .add(-1, "days")
            .format()
        ]
      },
      selectData: [],
      pageInfo: {
        loading: false,
        page: 1,
        total: 0
      },
      columnsOfDemo: [
        {
          type: "expand",
          width: 30,
          render: (h, params) => {
            return h(tableExpand, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          title: "设备ID",
          key: "deviceNo",
          align: "center"
        },
        {
          title: "设备名称",
          key: "alias",
          align: "center"
        },
        {
          title: "离线次数",
          key: "offlineCount",
          align: "center"
        },
        {
          title: "总离线时长",
          key: "totalTime",
          align: "center"
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let row = { ...params.row };
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    disabled: true
                  },
                  on: {
                    click: () => {
                      this.handelEdit(row);
                    }
                  }
                },
                "原因提交"
              )
            ]);
          }
        }
      ],
      columns: [
        {
          type: "expand",
          width: 30,
          render: (h, params) => {
            return h(tableExpand, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          title: "设备ID",
          key: "deviceNo",
          align: "center"
        },
        {
          title: "设备名称",
          key: "name",
          align: "center"
        },
        {
          title: "离线次数",
          key: "offlineCount",
          align: "center"
        },
        {
          title: "总离线时长",
          key: "totalTime",
          align: "center"
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let row = { ...params.row };
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.handelEdit(row);
                    }
                  }
                },
                "原因提交"
              )
            ]);
          }
        }
      ],
      tableData: [],
      formRules: {
        customerName: [
          {
            required: true,
            validator: validateAddress(
              "客服姓名",
              "客服姓名只能输入中文、字母、数字、下划线"
            ),
            trigger: "blur"
          }
        ],
        remark: [
          {
            required: true,
            validator: validateTitle("备注", "备注中不能含有特殊字符"),
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    _confirmAdd() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let params = { ...this.selectRow };
          addServiceLog(params).then(res => {
            if (res.code == 200) {
              this.$Message.success("提交成功！");
              this.modal = false;
            }
          });
        }
      });
    },

    handelEdit(row) {
      this.modal = true;
      this.$nextTick(_ => {
        this.$refs.formRef.resetFields();
        this.selectRow = {
          deviceNo: row.deviceNo,
          eventDate: this.moment(this.formHeader.timeRange[0]).format(
            "YYYY-MM-DD"
          ),
          type: 0,
          customerName: "",
          remark: ""
        };
      });
    },

    // 获取城市列表
    _getCityList() {
      let vm = this;
      getCityList().then(res => {
        if (res.code == 200) {
          vm.cityList = res.data;
          // vm.formHeader.cityId = res.data[2].id;
          // vm.formHeader.cityId = vm.cityList[2].id;
          // vm._getCompanyList();
        }
      });
    },

    // 查询事件
    _requireThing() {
      let vm = this;
      vm.pageInfo.page = 1;
      vm._getDeviceLogList();
    },

    // 城市变更
    _cityChange(id) {
      this.companyList = [];
      this.deviceList = [];
      this.formHeader.companyId = "";
      this.formHeader.deviceId = "";
      if (!!id) {
        this.formHeader.cityId = id;
        this._getCompanyList();
      }
    },

    // 企业变更
    _companyChange(id) {
      this.formHeader.deviceId = "";
      this.deviceList = [];
      if (!!id) {
        this.formHeader.companyId = id;
        this._getDeviceList();
      }
    },

    // 获取设备列表
    _getDeviceList() {
      let vm = this;
      let companyId = vm.formHeader.companyId;
      const params = {
        companyId
      };
      getDeviceListByCompany(params).then(res => {
        if (res.code == 200) {
          this.deviceList = [...res.data];
        }
      });
    },

    // 获取公司列表
    _getCompanyList() {
      let vm = this;
      let cityId = vm.formHeader.cityId;
      let params = {
        cityId
      };
      getCompanyListByCity(params).then(res => {
        if (res.code == 200) {
          this.companyList = [...res.data];
        }
      });
    },

    // 切换分页
    switchThePaging(index) {
      this.pageInfo.page = index;
      this._getDeviceLogList();
    },

    // 获取设备日志列表
    _getDeviceLogList() {
      let vm = this;
      vm.pageInfo.loading = true;
      let startTime = vm.moment(vm.formHeader.timeRange[0]).valueOf(),
        endTime = vm.moment(vm.formHeader.timeRange[1]).valueOf();
      if (startTime == endTime) {
        let today = this.moment(
          new Date(new Date().setHours(0, 0, 0, 0))
        ).valueOf();
        if (startTime == today) {
          endTime = this.moment().valueOf();
        } else {
          endTime = endTime + 86399999;
        }
      } else {
        endTime = endTime + 86399999;
      }
      let deviceId = vm.formHeader.deviceId;
      let companyId = vm.formHeader.companyId;
      const params = {
        page: vm.pageInfo.page,
        // size: 15,
        companyId,
        deviceId,
        startTime,
        endTime
      };
      getDeviceLogList(params).then(res => {
        if (res.code == 200 && !!res.data) {
          vm.tableData = res.data.list;
          vm.pageInfo.total = res.data.total;
          setTimeout(_ => {
            vm.pageInfo.loading = false;
          }, 500);
        } else {
          vm.pageInfo.loading = false;
          vm.tableData = [];
          vm.pageInfo.total = 0;
        }
      });
    }
  }
};
</script>
